

#include "lib_eeprom.h"


//void initEEPROM(const STEE *EE)
void initEEPROM(MODBUS_t EE)
{
	uint8_t  i=0;

	while (i<=64)
	{
//		uint8_t *p_f  = (uint8_t *) &(*EE).MODBUS.F[i];
		uint8_t *p_f  = (uint8_t *) &EE.F[i];

		uint8_t *p_al = (uint8_t *) &EE.A[i].byte.lo;
		uint8_t *p_ah = (uint8_t *) &EE.A[i].byte.hi;
		uint8_t *p_bl = (uint8_t *) &EE.B[i].byte.lo;
		uint8_t *p_bh = (uint8_t *) &EE.B[i].byte.hi;


		uint8_t f  = eeprom_read_byte ( p_f);	//	flag
		uint8_t al = eeprom_read_byte ( p_al);	//	1st copy (low)
		uint8_t ah = eeprom_read_byte ( p_ah);	//	1st copy (hi)
		uint8_t bl = eeprom_read_byte ( p_bl);	//	2nd inverted copy
		uint8_t bh = eeprom_read_byte ( p_bh);	//	2nd inverted copy


		if ( al!=~bl || ah!=~bh )	// если значения отличаються
		{
			if ( f == EEPROM_FLAG_OK ) {} //	такого быть не может
//////////////////////////////////////////////////////////////////////////////
			if ( f == EEPROM_FLAG_3 )		//	B false (l)
			{
				bl = ~al;
				eeprom_write_byte ( p_bl, bl);
				f = EEPROM_FLAG_4;
				eeprom_write_byte ( p_f, f);

			}
			if ( f == EEPROM_FLAG_4 )		//	B false (h)
			{
				bh = ~ah;
				eeprom_write_byte ( p_bh, bh);
				eeprom_write_byte ( p_f, EEPROM_FLAG_OK);
				//	all ok
			}
//////////////////////////////////////////////////////////////////////////////
			if ( f == EEPROM_FLAG_2 )		//	A false (h)
			{
				ah = ~bh;
				eeprom_write_byte ( p_ah, ah);
				f = EEPROM_FLAG_BEGIN;
				eeprom_write_byte ( p_f, f);
			}
			if ( f == EEPROM_FLAG_BEGIN )	//	A false (l)
			{
				al = ~bl;
				eeprom_write_byte ( p_al, al);
			}
		}

		// делаем копию в памяти

		i++;
	}
}

